package cn.auto.utility;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;

public class Utilities {

	public static HashMap<String, String> jsonToHashMap(JSONObject jo) {
		Iterator<?> keys = jo.keys();
		HashMap<String, String> hm = new HashMap<String, String>();
		while (keys.hasNext()) {
			String key = (String) keys.next();
			String value = jo.getString(key);
			hm.put(key, value);
		}
		return hm;
	}

	public static boolean generateImage(String imgStr, File file) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			byte[] b = decoder.decodeBuffer(imgStr);
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(file);
			out.write(b);
			out.flush();
			out.close();
			return true;
		} catch (Exception e) {
			System.out.println(e);
			return false;
		}
	}

	public static String getRandomString(int length) {
		// 随机字符串的随机字符库
		String KeyString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuffer sb = new StringBuffer();
		int len = KeyString.length();
		for (int i = 0; i < length; i++) {
			sb.append(KeyString.charAt((int) Math.round(Math.random() * (len - 1))));
		}
		return sb.toString();
	}

	public static String getMapValueByKey(HashMap<String, String> hm, String k) {
		Iterator<Map.Entry<String, String>> iter = hm.entrySet().iterator();
		String value=null;
		while(iter.hasNext()){
            Map.Entry<String, String> entry = iter.next();
            if (entry.getKey().equals(k)){
            	value=entry.getValue();
            	break;
            }
        }
		return value;
	}

}
